<script setup lang="ts">
import { ref } from "vue";
import IndexApi from "../api/index";
import { openDialog, getStore } from "../preload";
import wildcard from "wildcard";
const files: any = ref([]);
const copyFiles: any = ref([]);
const loading = ref(false);
const start = ref(false);
const resolvers: any = ref({});
getStore("resolvers").then((res: any) => {
    resolvers.value = res;
});
const errLen = ref(0);
const tableRef = ref();
const autoScroll = ref(true);
const doneLen = ref(0);
const showFiles = ref(false);
const onSubmit = async () => {
    loading.value = true;
    start.value = true;
    errLen.value = 0;
    doneLen.value = 0;
    for (let i = 0; i < files.value.length; i++) {
        files.value[i].status = 1;
        files.value[i].message = "解析中...";
        await onParse(i);
        if (autoScroll.value) {
            tableRef.value?.scrollToRow(i + 2);
        }
        doneLen.value++;
    }
    loading.value = false;
};
const indexs: any = ref([]);
const loadIndexs = () => {
    IndexApi.indexs().then((res: any) => {
        indexs.value = res.data || [];
    });
};
loadIndexs();
const onParse = async (index: number) => {
    let item = files.value[index];
    if (item.resolver !== "-") {
        let res = await IndexApi.create({
            index: form.value.index,
            filename: files.value[index].file,
            resolver: files.value[index].resolver,
        });
        if (res.code === 200) {
            item.status = 2;
            item.message = "OK";
        } else {
            item.status = 3;
            item.message = "失败 " + res.message;
            errLen.value++;
        }
    } else {
        item.status = 3;
        item.message = "失败 resolver is nil";
        errLen.value++;
    }
    files.value[index] = item;
};
const onOpenDialog = (value: string) => {
    openDialog([value, "multiSelections"]).then((res: any) => {
        if (res && res.filePaths && res.filePaths.length > 0) {
            onReadDir(res.filePaths);
        }
    });
};
const onReadDir = (dirs: any) => {
    IndexApi.readDir({ dirs: dirs }).then((res: any) => {
        let items = res.data || [];
        let list: any = [];
        for (let i = 0; i < items.length; i++) {
            let resolver = parseResolver(items[i]);
            list.push({
                file: items[i],
                resolver: resolver,
                message: resolver != "-" ? "" : "失败 resolver is nil",
                status: 0,
            });
        }
        files.value = files.value.concat(list);
        copyFiles.value = copyFiles.value.concat(list);
        showFiles.value = true;
    });
};
const parseResolver = (filename: string) => {
    let name = filename.split(/[\\/]/).pop() || "";
    let ext = name.split(".").pop() || name;
    return resolvers.value[ext] || "-";
};
const patterns = ref("");
const filterFile = () => {
    if (patterns.value == "") {
        files.value = copyFiles.value;
        return;
    }
    let items: any = [];
    for (let i = 0; i < copyFiles.value.length; i++) {
        if (wildcard(patterns.value, copyFiles.value[i].file)) {
            items.push(copyFiles.value[i]);
        }
    }
    files.value = items;
};
const onMouseenter = () => {
    autoScroll.value = false;
};
const onMouseleave = () => {
    autoScroll.value = true;
};
const preventDefault = (event: any) => {
    event.preventDefault();
    event.stopPropagation();
};
const handleDrop = (event: any) => {
    preventDefault(event);
    let data = event.dataTransfer.files;
    let items = [];
    for (let i = 0; i < data.length; i++) {
        items.push(data[i].path);
    }
    onReadDir(items);
};
const cleanFiles = () => {
    files.value = [];
    copyFiles.value = [];
    showFiles.value = false;
};
const form = ref({
    index: "",
});
const columns = [
    {
        key: "resolver",
        title: "解析器",
        dataKey: "resolver",
        class: "resolver-tag",
    },
    {
        key: "file",
        title: "文件路径",
        dataKey: "file",
        width: window.innerWidth - 145,
    },
    {
        key: "message",
        title: "信息",
        dataKey: "message",
        width: 100,
        align: "right",
        class: "!text-xs italic",
    },
];
const rowClass = ({ rowData }: any) => {
    if (rowData.resolver === "-") {
        return "text-red-500";
    }
    if (rowData.status === 1) {
        return "text-orange-500";
    } else if (rowData.status === 2) {
        return "text-gray-500";
    } else if (rowData.status === 3) {
        return "text-red-500";
    }
};
</script>
<template>
    <div class="w-screen h-screen fixed" @drop="handleDrop" @dragover="preventDefault" @dragenter="preventDefault">
        <div v-if="showFiles" class="w-full h-full flex flex-col px-3">
            <div class="my-2">
                <el-input v-model="patterns" @input="filterFile" placeholder="通配符匹配文件" clearable></el-input>
            </div>
            <div class="w-full h-0 flex-1 border rounded" @mouseenter="onMouseenter" @mouseleave="onMouseleave">
                <el-auto-resizer>
                    <template #default="{ height, width }">
                        <el-table-v2 ref="tableRef" :columns="columns" :data="files" :row-class="rowClass" :width="width" :height="height" :header-height="0" :row-height="35"></el-table-v2>
                    </template>
                </el-auto-resizer>
            </div>
            <div class="flex items-center py-3 gap-3">
                <div class="text-sm">
                    进度：
                    <span class="font-bold">{{`${doneLen}/${files.length}` }}</span>
                    <span v-if="errLen > 0" class="ml-4 text-red-400">失败：{{ errLen }}</span>
                </div>
                <el-button text size="small" type="danger" :disabled="loading" @click="cleanFiles">清空</el-button>
                <div class="flex-1"></div>
                <el-select class="!w-52" v-model="form.index" filterable allow-create default-first-option :teleported="false" :reserve-keyword="false" placeholder="索引" clearable>
                    <el-option v-for="(item,index) in indexs" :key="index" :label="item" :value="item" />
                </el-select>
                <el-button class="!ml-0" plain :disabled="loading" @click="onSubmit">开始解析</el-button>
            </div>
        </div>
        <div v-else class="flex items-center justify-center flex-col w-full h-full drag">
            <div class="flex items-center gap-4 -mt-10 no-drag">
                <el-button class="!py-12 w-28" text @click="onOpenDialog('openFile')">
                    <div>
                        <div class="mb-2 h-12"><i class="iconfont icon-file text-5xl"></i></div>
                        <div>导入文件</div>
                    </div>
                </el-button>
                <div class="text-gray-400 text-sm">-</div>
                <el-button class="!py-12 w-28" text @click="onOpenDialog('openDirectory')">
                    <div>
                        <div class="mb-2 h-12"><i class="iconfont icon-folder text-5xl"></i></div>
                        <div>导入文件夹</div>
                    </div>
                </el-button>
            </div>
            <div class="text-sm text-gray-400 mt-10"><i class="iconfont icon-import mr-1"></i>或者拖拽文件、文件夹至窗口进行导入</div>
        </div>
    </div>
</template>
<style scoped>
</style>
